package com.longagoewk.springboot.dao;

import com.longagoewk.springboot.LogConfig;
import com.longagoewk.springboot.entity.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDao {

    //JDBC访问数据模板
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /*
     * 获取用户实体
     * */
    public UserBean getUser(UserBean user)
    {
        String sql = "SELECT * FROM userinfo where username=?";
        try {
            return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(UserBean.class),user.getUsername());
        }catch (EmptyResultDataAccessException e)
        {
            LogConfig.error("数据库 - 用户"+user.getUsername()+"获取实体失败");
            return null;
        }
    }

    //更新用户密码
    public boolean updataUser(UserBean userBean){
        String sql = "UPDATE userinfo SET password = ? WHERE username = ?";
        try {
            int result = jdbcTemplate.update(sql,userBean.getPassword(),userBean.getUsername());
            return result > 0;
        } catch (DataAccessException e) {
            LogConfig.error("数据库 - 用户"+userBean.getUsername()+"更新密码失败");
            return false;
        }
    }

}
